<template>
  <div class="policy-management-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card mb-6 shadow-md hover:shadow-lg transition-shadow duration-300">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="保单编号" class="w-[220px]">
          <el-input v-model="searchForm.policyId" placeholder="请输入保单编号（模糊查询）" clearable size="small"></el-input>
        </el-form-item>
        <el-form-item label="投保人ID" class="w-[220px]">
          <el-input v-model="searchForm.insuredId" placeholder="请输入投保人ID（模糊查询）" clearable size="small"></el-input>
        </el-form-item>
        <el-form-item label="保险类型" class="w-[220px]">
          <el-select v-model="searchForm.insuranceCoverageName" placeholder="请选择保险类型" clearable size="small"
            style="width: 150px">
            <el-option label="小麦种植保险" value="小麦种植保险"></el-option>
            <el-option label="水稻种植保险" value="水稻种植保险"></el-option>
            <el-option label="玉米种植保险" value="玉米种植保险"></el-option>
            <el-option label="大豆种植保险" value="大豆种植保险"></el-option>
            <el-option label="生猪养殖保险" value="生猪养殖保险"></el-option>
            <el-option label="农业种植基本险" value="农业种植基本险"></el-option>
            <el-option label="能繁母猪养殖保险" value="能繁母猪养殖保险"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保单状态" class="w-[200px]">
          <el-select v-model="searchForm.policyStatus" placeholder="请选择保单状态" clearable size="small"
            style="width: 150px">
            <el-option label="待生效" value="1"></el-option>
            <el-option label="已生效" value="2"></el-option>
            <el-option label="已退保" value="3"></el-option>
            <el-option label="已过期" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleSearch" class="mr-2">
            <i class="el-icon-search mr-1"></i>查询
          </el-button>
          <el-button size="small" @click="resetSearch" class="mr-2">
            <i class="el-icon-refresh mr-1"></i>重置
          </el-button>
          <el-button type="success" size="small" @click="refreshList">
            <i class="el-icon-refresh-left mr-1"></i>刷新
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 投保单列表 -->
    <el-card class="policy-table-card shadow-md">
      <div class="table-container">
        <el-table :data="policyList" border stripe v-loading="loading" element-loading-text="加载中，请稍候..."
          element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.8)"
          style="width: 100%" @row-click="handleRowClick">
          <el-table-column prop="policyId" label="保单编号" width="180" align="center" fixed="left"></el-table-column>
          <el-table-column prop="insuredId" label="投保人ID" width="140" align="center"></el-table-column>
          <el-table-column prop="insuranceCoverageName" label="保险类型" width="140" align="center"></el-table-column>
          <el-table-column label="承保数量" width="120" align="center"
            :formatter="formatCoverageQuantity"></el-table-column>
          <el-table-column prop="startDate" label="保险起期" width="120" align="center"></el-table-column>
          <el-table-column prop="endDate" label="保险止期" width="120" align="center"></el-table-column>
          <el-table-column prop="sumInsured" label="总保额(元)" width="110" align="right"></el-table-column>
          <el-table-column prop="totalPremium" label="总保费(元)" width="110" align="right"></el-table-column>
          <!-- 缴费状态列 -->
          <el-table-column prop="payStatus" label="缴费状态" width="100" align="center">
            <template #default="scope">
              <span v-if="scope.row.payStatus == 1">待缴费</span>
              <span v-if="scope.row.payStatus == 2">缴费中</span>
              <span v-if="scope.row.payStatus == 3">缴费成功</span>
              <span v-if="scope.row.payStatus == 4">缴费失败</span>
            </template>
          </el-table-column>
          <!-- 保单状态列 -->
          <el-table-column prop="policyStatus" label="保单状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.policyStatus)"
                :class="scope.row.policyStatus === 3 ? 'bg-red-500' : ''" class="cursor-default">
                {{ formatPolicyStatus(scope.row.policyStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="投保时间" width="160" align="center"></el-table-column>
          <!-- 操作列 -->
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="scope">
              <!-- 详情按钮 -->
              <el-button type="text" size="small" @click="handleViewDetail(scope.row.orderId)"
                class="text-blue-600 hover:text-blue-800 transition-colors mr-3">
                <i class="el-icon-view mr-1"></i>详情
              </el-button>

              <!-- 删除按钮 -->
              <el-button type="text" size="small" @click="handleDeletePolicy(scope.row.orderId, scope.row.policyId)"
                class="text-red-600 hover:text-red-800 transition-colors"
                v-if="[1, 2].includes(scope.row.policyStatus)">
                <i class="el-icon-delete mr-1"></i>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页控件 -->
      <div class="pagination-container mt-4 flex justify-end items-center">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" background></el-pagination>
      </div>
    </el-card>

    <!-- 1. 详情弹窗 -->
    <el-dialog title="投保单详情" v-model="detailDialogVisible" width="600px" :close-on-click-modal="false"
      :before-close="handleDetailDialogClose">
      <div class="detail-container" v-loading="detailLoading">
        <!-- 基础信息区域 -->
        <div class="detail-section mb-4">
          <h3 class="section-title text-lg font-semibold mb-3">基础信息</h3>
          <el-form :model="currentPolicy" label-width="120px" class="detail-form">
            <el-form-item label="保单编号">
              <el-input v-model="currentPolicy.policyId" disabled></el-input>
            </el-form-item>
            <el-form-item label="投保人ID">
              <el-input v-model="currentPolicy.insuredId" disabled></el-input>
            </el-form-item>
            <el-form-item label="保险类型">
              <el-input v-model="currentPolicy.insuranceCoverageName" disabled></el-input>
            </el-form-item>
            <el-form-item label="投保项目">
              <el-input v-model="currentPolicy.insuranceSubject" disabled></el-input>
            </el-form-item>
          </el-form>
        </div>

        <!-- 承保信息区域 -->
        <div class="detail-section mb-4">
          <h3 class="section-title text-lg font-semibold mb-3">承保信息</h3>
          <el-form :model="currentPolicy" label-width="120px" class="detail-form">
            <el-form-item label="承保面积(亩)" v-if="currentPolicy.coverageArea">
              <el-input v-model="currentPolicy.coverageArea" disabled></el-input>
            </el-form-item>
            <el-form-item label="承保数量(头/只)" v-if="currentPolicy.coverageQuantity">
              <el-input v-model="currentPolicy.coverageQuantity" disabled></el-input>
            </el-form-item>
            <el-form-item label="单位保额(元)">
              <el-input v-model="currentPolicy.unitInsured" disabled></el-input>
            </el-form-item>
            <el-form-item label="总保额(元)">
              <el-input v-model="currentPolicy.sumInsured" disabled></el-input>
            </el-form-item>
            <el-form-item label="总保费(元)">
              <el-input v-model="currentPolicy.totalPremium" disabled></el-input>
            </el-form-item>
          </el-form>
        </div>

        <!-- 时间与状态区域 -->
        <div class="detail-section mb-4">
          <h3 class="section-title text-lg font-semibold mb-3">时间与状态</h3>
          <el-form :model="currentPolicy" label-width="120px" class="detail-form" :rules="statusFormRules"
            ref="statusForm">
            <el-form-item label="保险起期">
              <el-input v-model="currentPolicy.startDate" disabled></el-input>
            </el-form-item>
            <el-form-item label="保险止期">
              <el-input v-model="currentPolicy.endDate" disabled></el-input>
            </el-form-item>
            <el-form-item label="缴费状态">
              <el-input :value="formatPayStatus(currentPolicy.payStatus)" disabled></el-input>
            </el-form-item>
            <!-- 保单状态修改：可编辑 -->
            <el-form-item label="保单状态" prop="newPolicyStatus">
              <el-select v-model="currentPolicy.newPolicyStatus" placeholder="请选择新状态">
                <el-option v-for="(status, key) in policyStatusOptions" :key="key" :label="status" :value="key"
                  :disabled="!isStatusChangeable(currentPolicy.policyStatus, key)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态变更原因">
              <el-input v-model="currentPolicy.statusChangeReason" placeholder="请输入状态变更原因（选填）" type="textarea"
                rows="2"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 弹窗底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmStatusChange">保存状态修改</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 2. 删除确认弹窗 -->
    <el-dialog title="确认删除" v-model="deleteDialogVisible" width="30%" :close-on-click-modal="false">
      <div>
        <p class="text-red-500">您确定要删除保单编号为 {{ deletePolicyId }} 的记录吗？</p>
        <p class="text-gray-500 text-sm mt-2">删除后数据将无法恢复，请谨慎操作。</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import hxxp from "@/utils/hxxp";

// 获取组件实例（用于表单验证）
const { proxy } = getCurrentInstance();

// 状态管理
const policyList = ref([]);
const loading = ref(false);
const detailLoading = ref(false);
const detailDialogVisible = ref(false);
const deleteDialogVisible = ref(false);

// 当前操作的保单ID
const deletePolicyId = ref('');
const currentOrderId = ref(null);

// 当前操作的保单数据
const currentPolicy = ref({
  orderId: '',
  policyId: '',
  insuredId: '',
  insuranceCoverageName: '',
  insuranceSubject: '',
  coverageArea: '',
  coverageQuantity: '',
  unitInsured: '',
  sumInsured: '',
  totalPremium: '',
  startDate: '',
  endDate: '',
  payStatus: '',
  policyStatus: '',
  newPolicyStatus: '',
  statusChangeReason: '',
  createTime: ''
});

// 搜索表单 - 修改保险类型参数为insuranceCoverageName
const searchForm = reactive({
  policyId: '',
  insuredId: '',
  insuranceCoverageName: '',  // 修改参数名
  policyStatus: ''
});

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 保单状态选项
const policyStatusOptions = {
  1: '待生效',
  2: '已生效',
  3: '已退保',
  4: '已过期'
};

// 状态修改表单验证规则
const statusFormRules = {
  newPolicyStatus: [
    { required: true, message: '请选择新的保单状态', trigger: 'change' }
  ]
};

// 页面加载时获取保单列表
onMounted(() => {
  fetchPolicyList();
});

// 行点击事件（用于调试）
const handleRowClick = (row) => {
  console.log('当前行数据:', row);
  console.log('行数据是否包含orderId:', 'orderId' in row);
};

// 1. 获取保单列表数据 - 调整参数名以匹配后端接口
const fetchPolicyList = () => {
  loading.value = true;
  const params = {
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize,
    policyId: searchForm.policyId,
    insuredId: searchForm.insuredId,
    insuranceCoverageName: searchForm.insuranceCoverageName,  // 修改参数名
    policyStatus: searchForm.policyStatus
  };

  hxxp.get('/aiInsureOrder/list', { params })
    .then(response => {
      loading.value = false;
      console.log(response)
      if (response.code === 100200) {
        policyList.value = response.data.list;
        pagination.total = response.data.total;
      } else {
        ElMessage.error(response.msg || '查询保单列表失败');
      }
    })
    .catch(error => {
      loading.value = false;
      console.error('查询保单列表失败', error);
      ElMessage.error('网络异常，查询保单列表失败');
    });
};

// 2. 搜索/重置/刷新
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchPolicyList();
};

const resetSearch = () => {
  searchForm.policyId = '';
  searchForm.insuredId = '';
  searchForm.insuranceCoverageName = '';  // 修改参数名
  searchForm.policyStatus = '';
  pagination.currentPage = 1;
  fetchPolicyList();
};

const refreshList = () => {
  fetchPolicyList();
  ElMessage.success('列表已刷新');
};

// 3. 分页相关
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchPolicyList();
};

const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  fetchPolicyList();
};

// 4. 格式化辅助函数
const formatCoverageQuantity = (row) => {
  if (row.coverageArea) {
    return `${Number(row.coverageArea).toFixed(2)} 亩`;
  } else if (row.coverageQuantity) {
    return `${row.coverageQuantity} 头/只`;
  }
  return '-';
};

const formatPayStatus = (status) => {
  const payStatusMap = {
    1: '待缴费',
    2: '缴费中',
    3: '缴费成功',
    4: '缴费失败'
  };
  return payStatusMap[status] || '未知状态';
};

const formatPolicyStatus = (status) => {
  return policyStatusOptions[status] || '未知状态';
};

const getStatusTagType = (status) => {
  const typeMap = {
    1: 'warning',
    2: 'success',
    3: 'warning',
    4: 'info'
  };
  return typeMap[status] || 'default';
};

// 5. 详情弹窗相关
const handleViewDetail = (orderId) => {
  console.log('触发详情按钮点击，orderId:', orderId);

  if (!orderId) {
    ElMessage.error('缺少保单ID，无法查看详情');
    return;
  }

  currentOrderId.value = orderId;
  detailLoading.value = true;

  hxxp.get(`/aiInsureOrder/get/${orderId}`)
    .then(response => {
      detailLoading.value = false;
      if (response.code === 100200) {
        const policyData = response.data;
        const formattedData = {
          ...policyData,
          insuranceSubject: policyData.insuranceSubject || '未填写',
          coverageArea: policyData.coverageArea ? Number(policyData.coverageArea).toFixed(2) : '',
          coverageQuantity: policyData.coverageQuantity || '0',
          unitInsured: Number(policyData.unitInsured || 0).toFixed(2),
          sumInsured: Number(policyData.sumInsured || 0).toFixed(2),
          totalPremium: Number(policyData.totalPremium || 0).toFixed(2),
          newPolicyStatus: policyData.policyStatus + '',
          statusChangeReason: ''
        };

        currentPolicy.value = formattedData;

        nextTick(() => {
          detailDialogVisible.value = true;
        });
      } else {
        ElMessage.error(response.data.msg || '获取保单详情失败');
      }
    })
    .catch(error => {
      detailLoading.value = false;
      console.error('获取保单详情失败', error);
      ElMessage.error('网络异常，获取保单详情失败');
    });
};

// 关闭详情弹窗
const handleDetailDialogClose = () => {
  detailDialogVisible.value = false;
  currentPolicy.value.newPolicyStatus = '';
  currentPolicy.value.statusChangeReason = '';
  currentOrderId.value = null;

  const statusForm = proxy.$refs.statusForm;
  if (statusForm) statusForm.resetFields();
};

// 6. 保单状态修改
const confirmStatusChange = () => {
  const statusForm = proxy.$refs.statusForm;

  if (!statusForm) {
    ElMessage.error('表单初始化失败');
    return;
  }

  statusForm.validate((isValid) => {
    if (!isValid) return;

    if (currentPolicy.value.policyStatus + '' === currentPolicy.value.newPolicyStatus) {
      ElMessage.warning('新状态与当前状态一致，无需修改');
      detailDialogVisible.value = false;
      return;
    }

    loading.value = true;
    hxxp.post('/aiInsureOrder/updateStatus', {
      orderId: currentPolicy.value.orderId,
      policyId: currentPolicy.value.policyId,
      policyStatus: currentPolicy.value.newPolicyStatus,
      statusChangeReason: currentPolicy.value.statusChangeReason || '管理员手动修改'
    })
      .then(response => {
        loading.value = false;
        if (response.code === 100200) {
          ElMessage.success('保单状态修改成功');
          detailDialogVisible.value = false;
          fetchPolicyList();
        } else {
          ElMessage.error(response.msg || '修改保单状态失败');
        }
      })
      .catch(error => {
        loading.value = false;
        console.error('修改保单状态失败', error);
        ElMessage.error('网络异常，修改保单状态失败');
      });
  });
};

// 7. 删除相关
const handleDeletePolicy = (orderId, policyId) => {
  console.log('触发删除按钮点击，orderId:', orderId, 'policyId:', policyId);

  if (!orderId || !policyId) {
    ElMessage.error('数据不完整，无法删除');
    return;
  }

  currentOrderId.value = orderId;
  deletePolicyId.value = policyId;

  nextTick(() => {
    deleteDialogVisible.value = true;
  });
};

const confirmDelete = () => {
  if (!currentOrderId.value) {
    ElMessage.error('未获取到投保单ID，无法删除');
    return;
  }

  loading.value = true;
  hxxp.delete(`/aiInsureOrder/delete/${currentOrderId.value}`)
    .then(response => {
      loading.value = false;
      if (response.code === 100200) {
        ElMessage.success('保单删除成功');
        deleteDialogVisible.value = false;
        fetchPolicyList();
      } else {
        ElMessage.error(response.msg || '删除保单失败');
      }
    })
    .catch(error => {
      loading.value = false;
      console.error('删除保单失败', error);
      ElMessage.error('网络异常，删除保单失败');
    });
};

// 8. 判断状态是否可变更
const isStatusChangeable = (currentStatus, targetStatus) => {
  if (targetStatus === 3) return true;
  const allowTransitions = {
    1: [2, 3, 4],
    2: [3, 4],
    3: [],
    4: []
  };
  return allowTransitions[currentStatus]?.includes(Number(targetStatus)) || false;
};
</script>

<style scoped>
.policy-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  overflow: auto;
}

::v-deep .el-dialog {
  z-index: 9999 !important;
}

::v-deep .el-dialog__wrapper {
  z-index: 9999 !important;
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e5e7eb;
}

.filter-card {
  border-radius: 8px;
  overflow: hidden;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.table-container {
  overflow-x: auto;
}

.pagination-container {
  padding: 10px 0;
}

/* 详情弹窗样式 */
.detail-container {
  padding: 10px 0;
}

.detail-section {
  border-bottom: 1px dashed #e5e7eb;
  padding-bottom: 15px;
}

.section-title {
  color: #333;
  border-left: 4px solid #409eff;
  padding-left: 8px;
}

.detail-form {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

@media (max-width: 768px) {
  .detail-form {
    grid-template-columns: 1fr;
  }
}

::v-deep .el-tag.bg-red-500 {
  background-color: #f56c6c !important;
  border-color: #f56c6c !important;
}

@media (max-width: 1200px) {
  .search-form {
    gap: 8px;
  }

  .el-form-item {
    margin-bottom: 10px !important;
  }
}

@media (max-width: 768px) {
  .policy-management-container {
    padding: 10px;
  }

  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .el-form-item {
    width: 100% !important;
  }

  .pagination-container {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
}
</style>
